<?php
session_start();
require_once "WxApi.php";
require_once "WxConfig.php";
require_once(dirname(__FILE__) . '/../jssdk.php');


$appId = WxConfig::APPID;
$appSecret = WxConfig::APPSECRET;
$jssdk = new JSSDK($appId, $appSecret);
$signPackage = $jssdk->GetSignPackage();
$g_AccessToken = $jssdk->getAccessToken();
//①、获取用户openid
$tools = new WxApi();


$userInfo = "";
$uid = @$_SESSION['uid'];

if (!isset($uid)) {
    $api_userinfo = $tools->GetUserInfo();
    $openid_str = $api_userinfo['openid'];
    if ($openid_str) {
        //是否存在该 openid
        $row = $dosql->GetOne("SELECT * FROM `#@__user` WHERE openid='$openid_str'");
        $t_time = time();

        if (is_array($row) && isset($row['id'])) {
            // 返回用户 id
            $uid = $row['id'];
            $openid = $openid_str;
            $_SESSION['uid'] = $uid;
            $_SESSION['openid'] = $openid_str;
            $userInfo = $row;
            $_SESSION['level'] = $row['level'];
            $level = $row['level'];
            $isadmin = $row['isadmin'];

        } else {
            if ($openid_str) {
//                $getUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $g_AccessToken . "&openid=" . $openid_str;
//                $res2 = json_decode(httpGet($getUserInfoUrl), true);
                //$userInfo = $api_userinfo;
                $res2 = $api_userinfo;
            }
            //获取用户信息

            $nickname = isset($res2['nickname']) ? $res2['nickname'] : "";
            $headimgurl = isset($res2['headimgurl']) ? $res2['headimgurl'] : "";
            $sex = isset($res2['sex']) ? $res2['sex'] : "";
            $country = isset($res2['country']) ? $res2['country'] : "";
            $province = isset($res2['province']) ? $res2['province'] : "";
            $city = isset($res2['city']) ? $res2['city'] : "";
            $subscribe_time = isset($res2['subscribe_time']) ? $res2['subscribe_time'] : 0;   //最后一次关注时间

            //新建用户
            $sql2 = "insert into `#@__user`(openid,nickname,headimgurl,sex,country,province,city,regtime,subscribe_time,level) values ('$openid_str','$nickname','$headimgurl','$sex','$country','$province','$city','$t_time','$subscribe_time','6')";
            $dosql->ExecNoneQuery($sql2);
            $uid = $dosql->GetLastID();
            $openid = $openid_str;
            $_SESSION['uid'] = $uid;
            $_SESSION['openid'] = $openid_str;
            $level = 6;
            $isadmin = 0;
        }
    }
} else {
    //有session 从数据库中读取用户名信息
    $uid = $_SESSION['uid'];
    $row = $dosql->GetOne("SELECT * FROM `#@__user` WHERE id='$uid'");
    if (is_array($row) && isset($row['id'])) {
        // 返回用户 id
        $uid = $row['id'];
        $_SESSION['uid'] = $uid;
        $openid = $row['openid'];
        $_SESSION['openid'] = $openid;
        $userInfo = $row;
        $_SESSION['level'] = $row['level'];
        $level = $row['level'];
        $isadmin = $row['isadmin'];
    }
}


function httpGet($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
    // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    //curl_setopt($curl,CURLOPT_CAINFO,dirname(__FILE__).'/cacert.pem');//这是根据http://curl.haxx.se/ca/cacert.pem 下载的证书，添加这句话之后就运行正常了
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}


//微信发送消息模板 函数

// json 为json格式的数据

function sendWxMsg($json)
{
    //发送消息
    global $g_AccessToken;
    if (isset($g_AccessToken)) {
        $uuu = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $g_AccessToken;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uuu);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //https协议
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        $html = curl_exec($ch);
        $txt_name = dirname(__FILE__) . "/txt/" . time() . "-sendWxMsg.txt";
        file_put_contents($txt_name, serialize($html));
    }

}


function getManage($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT * FROM `#@__user` WHERE id='$mid' ORDER BY id desc");
        if (is_array($m) && isset($m['id'])) {
            return $m['truename'];
        }
    }
}


/*
 * 函数说明：获取 多个工作人员 的名称
 *
 * @access  public
 * @param   $id   int  碎片ID
 * @param   $t    int  调用的内容 0为内容 1为标识名称 2为缩略图 3为跳转连接
 * @return  string     返回碎片缩略图地址
 */
function GetMembersName($ids = 0)
{
    global $dosql;
    if ($ids != "") {
        $men_names = "";
        $member = explode(",", $ids);
        if (count($member) > 1) {
            $i = 0;
            foreach ($member as $v) {
                $i++;
                if ($i < count($member)) {
                    $men_names .= getManage($v) . " ";
                } else {
                    $men_names .= getManage($v);
                }
            }
        } else {
            $men_names = getManage($ids);
        }
        return $men_names;
    } else {
        return "";
    }
}



function getManageUid($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT * FROM `#@__user` WHERE openid='$mid' ORDER BY id desc");
        if (is_array($m) && isset($m['id'])) {
            return $m['id'];
        }
    }
}


function getManageOpenidFromUid($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT `openid` FROM `#@__user` WHERE id='$mid' ORDER BY id desc");
        if (is_array($m) && isset($m['openid'])) {
            return $m['openid'];
        }
    }
}


function getFeeFromType($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT * FROM `#@__task` WHERE id='$mid' ORDER BY id desc");
        if (is_array($m) && isset($m['id'])) {
            return $m['value'];
        }
    }
}


function getRepairMode($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT p.`classname`,t.`title` FROM `#@__task` as t left join `#@__tasktype` as p  on t.classid=p.id  WHERE t.id='$mid' ");
        if (is_array($m) && isset($m['title'])) {
            return $m['classname'] . "-" . $m['title'];
        }
    }

}

function getTypeNameFromTask($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT p.`classname`,t.`title` FROM `#@__task` as t left join `#@__tasktype` as p  on t.classid=p.id  WHERE t.id='$mid' ");
        if (is_array($m) && isset($m['title'])) {
            return $m['classname'];
        }
    }

}

function getTypeName($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT t.`classname` FROM `#@__tasktype` as t  WHERE t.id='$mid' ");
        if (is_array($m) && isset($m['classname'])) {
            return $m['classname'];
        }
    }

}

function getTaskName($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT t.`title` FROM `#@__task` as t  WHERE t.id='$mid' ");
        if (is_array($m) && isset($m['title'])) {
            return $m['title'];
        }
    }

}


function getDeviceName($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT * FROM `#@__cascadedata` WHERE   datagroup='device' AND  datavalue='$mid'  ORDER BY id desc");
        if (is_array($m) && isset($m['id'])) {
            return $m['dataname'];
        }
    }
}


function getJinDuName($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT * FROM `#@__cascadedata` WHERE   datagroup='jindu' AND  datavalue='$mid'  ORDER BY id desc");
        if (is_array($m) && isset($m['id'])) {
            return $m['dataname'];
        }
    }
}

function getProjectStatus($mid)
{
    switch ($mid) {
        case 3:
            $order_title = "待接单";
            break;
        case 4:
            $order_title = "工程施工中";
            break;
        case 5:
            $order_title = "工程竣工";
            break;
        case 6:
            $order_title = "项目验收中";
            break;
        case 7:
            $order_title = "验收通过";
            break;
        default:
            $order_title = "全部";
    }
    return $order_title;
}


/*
 自动计算加班费
int $fee   费用标准
int $signInTime   签到时间
int $cfg_jiabanfei 加班每小时奖励

*/
function autoSumFee($fee, $signInTime, $cfg_jiabanfei)
{


    // 计算 费用
    // 获取最后一次签到时间
    $getFee = 0;
    $time_now = time();
    //计算 施工时间
    $hour_now = date("H", time());
    //加班
    $hour_18 = date("Y-m-d 18:00:00");
    $fenge_time = strtotime($hour_18);


    // 加班情况
    if ($hour_now < 18) {
        //没有加班

        $min_count = ($time_now - $signInTime) / 60; //施工分钟数
        $min_fee = $fee / 600; //每分钟的数值
        $getFee = ceil($min_count * $min_fee);

    } else {

        //加班跨时段
        if ($signInTime < $fenge_time) {
            //正常时段
            //精确到分钟
            $min_count = ($fenge_time - $signInTime) / 60; //施工分钟数
            $min_fee = $fee / 600; //每分钟的数值
            $getFee = ceil($min_count * $min_fee);
            if($getFee>260){
                $getFee=260;
            }
            //加班时段
            $hour2 = ($time_now - $fenge_time) / 3600;
            $hour2 = round($hour2, 2);
            // 加班时间最多按4个小时算
            //不足4小时的，精确到分钟
            if ($hour2 < 4) {
                $getFee += ceil(($time_now - $fenge_time) * ($cfg_jiabanfei / 3600));
            } else {
                $getFee += $cfg_jiabanfei * 4;
            }

        } else {


            $getFee = ceil(($time_now - $signInTime) * ($cfg_jiabanfei / 3600));

        }


    }
    return $getFee;
}


?>